<template>
  <MyModal ref="myModal" title="设置分组" :top="35">
    <template #content>
      <div style="display: grid; place-items: center">
        <a-form ref="loginForm" :model="formState" style="width: 360px">
          <a-form-item has-feedback name="groupId" label="请选择分组">
            <a-select v-model:value="formState.groupId" placeholder="请选择">
              <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
                {{ item.groupName }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item style="text-align: center">
            <a-button type="primary" style="border-radius: 6px" block @click="handleSubmit">
              确定
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import * as accountApi from '@/api/account'
import { message } from 'ant-design-vue'

const myModal = ref()

const selectedRowKey = ref<Array<any>>([])

let onlyType = ref<string>('wx')
const showModal = (idList: any, type = 'wx') => {
  onlyType.value = type
  selectedRowKey.value = idList
  getGroupList()
  myModal.value?.showModal()
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

interface formState {
  groupId: string
}
const formState = ref<formState>({
  groupId: '',
})

import type { SelectProps } from 'ant-design-vue'
const groupList = ref<SelectProps['options']>([])
const getGroupList = async () => {
  let api = null
  onlyType.value === 'wx'
    ? (api = accountApi.getWechatRobotGroupList())
    : (api = accountApi.getFishRobotGroupList())
  try {
    let { state, data, message: msg } = await api
    if (state === 200) {
      groupList.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const handleSubmit = async () => {
  const params = {
    groupId: formState.value.groupId,
    robotIds: selectedRowKey.value,
  }
  let api = null
  onlyType.value === 'wx'
    ? (api = accountApi.wechatRobotAddGroup(params))
    : (api = accountApi.fishRobotAddGroup(params))
  try {
    let { state, data, message: msg } = await api
    if (state === 200) {
      message.success('添加成功')
      emit('refresh')
      myModal.value.cancelModal()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
</script>
